﻿
using LocalNas.Application.Service.Auth.Dto;
using LocalNas.Application.Service.Dto;
using LocalNas.Core.Const;
using LocalNas.Core.Option;
using Microsoft.Extensions.Options;

namespace LocalNas.Application.Service;

[ApiDescriptionSettings(ConstSwaggerGroup.NAS平台, Name = "授权服务", Order = 100)]
public class AuthService : IDynamicApiController, ITransient
{
    private readonly RefreshTokenOptions _refreshTokenOptions;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly SqlSugarRepository<SysUser> _sysUserRep;

    public AuthService(
        IOptions<RefreshTokenOptions> refreshTokenOptions,
        IHttpContextAccessor httpContextAccessor,
        SqlSugarRepository<SysUser> sysUserRep)
    {
        _refreshTokenOptions = refreshTokenOptions.Value;
        _httpContextAccessor = httpContextAccessor;
        _sysUserRep = sysUserRep;
    }


    /// <summary>
    /// 获取所有硬盘
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [SuppressMonitor]
    [HttpPost("/Auth/Login")]
    public async Task<LoginResult> Login(LoginReuqest request)
    {
        var encryptPassword = MD5Encryption.Encrypt(request.Password); // 加密密码
        var user = await _sysUserRep.GetFirstAsync(x => x.Account == request.Account && x.Password == encryptPassword);
        if (user == null) throw Oops.Oh("账号或者密码错误");

        // 生成Token令牌
        var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
        {
            {ClaimConst.UserId, user.Id},
            {ClaimConst.Name, user.Name},
            {ClaimConst.Account, user.Account},
            {ClaimConst.UserType, user.UserType},
        });

        // 生成刷新Token令牌
        var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, _refreshTokenOptions.ExpiredTime);
        // 设置响应报文头
        _httpContextAccessor.HttpContext.SetTokensOfResponseHeaders(accessToken, refreshToken);

        return new LoginResult
        {
            Account = user.Account,
            Name = user.Name,
            UserType = user.UserType.ToString(),
            UserId = user.Id,
            //Token = accessToken,
            //RefreshToken = refreshToken
        };
    }

    [HttpGet("/Auth/GetLoginInfo")]
    public async Task<LoginResult> GetLoginInfo()
    {
        long.TryParse(App.User.FindFirst(ClaimConst.UserId)?.Value, out long userId);
        var user = await _sysUserRep.GetFirstAsync(x => x.Id == userId);
        return new LoginResult
        {
            Account = user.Account,
            Name = user.Name,
            UserType = user.UserType.ToString(),
            UserId = user.Id,
        };
    }

}
